package com.espressif.iot.ui.device.timer;

import org.json.JSONException;
import org.json.JSONObject;

import com.xiquezhijia.iot.R;
import com.espressif.iot.command.device.IEspCommandLight;
import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.type.device.timer.EspDeviceFixedTimeTimer;
import com.espressif.iot.type.device.timer.EspDeviceTimer;
import com.espressif.iot.type.device.timer.EspDeviceTimerJSONKey;
import com.espressif.iot.ui.device.dialog.ColorPlateDialog;
import com.espressif.iot.ui.device.dialog.ColorPlateDialog.OnSaveColorListener;

import com.espressif.iot.user.IEspUser;
import com.espressif.iot.user.builder.BEspUser;
import com.espressif.iot.util.EspStrings;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;



public abstract class DeviceTimerEditActivityAbs extends Activity implements EspDeviceTimerJSONKey, IEspCommandLight
{
    protected IEspDevice mDevice;
    
    protected IEspUser mUser;
    
    /**
     * The timer need edit. If null, create a new timer.
     */
    protected EspDeviceTimer mTimer;
    
    protected String[] mActionTitles;
    protected String[] mActionValues;
    
    /**
     * Get the JSONObject which need Post
     * 
     * @return
     */
    abstract protected JSONObject getPostJSON();
    
    /**
     * If edit exist timer, set the data on ContentView;
     */
    abstract protected void setGotData();
    
    protected final static int MENU_ID_SAVE = 0;
    
    protected Bundle mIntentBundle;
    
    
    protected Spinner mActionSpinner;
    
    protected ArrayAdapter<String> mActionsAdapter;
    
    //色盘颜色值存储文本
    TextView mActionTitle;
    protected View colordisplay;
    protected int color;
    protected int bright;
    protected boolean isOn;
    protected int frequency;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        mUser = BEspUser.getBuilder().getInstance();
        
        Intent intent = getIntent();
        String deviceKey = intent.getStringExtra(EspStrings.Key.DEVICE_KEY_KEY);
        mDevice = mUser.getUserDevice(deviceKey);
        long timerId = intent.getLongExtra(EspStrings.Key.DEVICE_TIMER_ID_KEY, -1);
        if (timerId >= 0)
        {
            for (int i = 0; i < mDevice.getTimerList().size(); i++)
            {
                EspDeviceTimer timer = mDevice.getTimerList().get(i);
                if (timer.getId() == timerId)
                {
                    mTimer = timer;
                    break;
                }
            }
        }
        
        mIntentBundle = intent.getBundleExtra(EspStrings.Key.DEVICE_TIMER_BUNDLE_KEY);
        
        mActionTitles = getActionTitles();
        mActionValues = getActionValues();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(Menu.NONE, MENU_ID_SAVE, 0, R.string.esp_device_timer_menu_save)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case MENU_ID_SAVE:
                JSONObject json = getPostJSON();
                if (json != null) {
                    new SaveTask().execute(json);
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * if the time is less than 10, add head '0'. EX: 8 -> 08
     * 
     * @param time
     * @return
     */
    protected String matchingTimeStr(int time)
    {
        String str = time + "";
        if (str.length() < 2)
        {
            str = "0" + str;
        }
        return str;
    }
    
    private class SaveTask extends AsyncTask<JSONObject, Void, Boolean>
    {
        
        private ProgressDialog mDialog;
        
        @Override
        protected void onPreExecute()
        {
            mDialog = new ProgressDialog(DeviceTimerEditActivityAbs.this);
            mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
            mDialog.setCancelable(false);
            mDialog.show();
        }
        
        @Override
        protected Boolean doInBackground(JSONObject... params)
        {
            JSONObject timerJSON = params[0];
            return mUser.doActionDeviceTimerPost(mDevice, timerJSON);
        }
        
        protected void onPostExecute(Boolean result)
        {
            mDialog.dismiss();
            mDialog = null;
            
            Activity activity = DeviceTimerEditActivityAbs.this;
            if (result)
            {
                Toast.makeText(activity, R.string.esp_device_timer_save_result_success, Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                finish();
            }
            else
            {
                Toast.makeText(activity, R.string.esp_device_timer_save_result_failed, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    private String[] getActionTitles()
    {
        switch (mDevice.getDeviceType())
        {
            case PLUG:
                return getResources().getStringArray(R.array.esp_device_plug_timer_actions);
            case PLUGS:
                return getResources().getStringArray(R.array.esp_device_plugs_timer_actions);
            default:
                return null;
        }
    }
    
    private String[] getActionValues()
    {
        switch (mDevice.getDeviceType())
        {
            case PLUG:
                return getResources().getStringArray(R.array.esp_device_plug_timer_action_values);
            case PLUGS:
                return getResources().getStringArray(R.array.esp_device_plugs_timer_action_values);
            default:
                return null;
        }
    }
    
    protected View GetTimerActionView() {
		// TODO Auto-generated method stub
		switch(mDevice.getDeviceType()){
			case PLUG:
				return GetPlugTimerActionView();
				
			case PLUGS:
				break;
			case LIGHT:
				return GetLightTimerActionView();
				
			default:
				break;
			
		}
		return null;
	}
    protected View GetLightTimerActionView() {
		// TODO Auto-generated method stub
      View view = getLayoutInflater().inflate(R.layout.timer_action_colorplate, null);
  	  mActionTitle = (TextView)view.findViewById(R.id.timer_action_text);
  	  colordisplay = (View)view.findViewById(R.id.color_plate);
  	  colordisplay.setOnClickListener(new colorpicklisten());
        if(mTimer != null)
        {
	           //EspDeviceFixedTimeTimer timer = (EspDeviceFixedTimeTimer)mTimer;
	           String action = getTimerAction(mTimer);
	           try {
				JSONObject lightpara = new JSONObject(action);
				
				if(lightpara != null){
					int red = lightpara.getInt(Red);
					int green = lightpara.getInt(Green);
					int blue = lightpara.getInt(Blue);
					int bright = lightpara.getInt(Bright);
					color=Color.rgb(red,green,blue);
					this.bright = bright;
					
					
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	           colordisplay.setBackgroundColor(color);
	           mActionTitle.setText(action);
	          
        }else{
        	mActionTitle.setText("R=? G=? B=? BRI=?");
        }
		return view;
	}
    
    protected class colorpicklisten implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final ColorPlateDialog colordialog = new ColorPlateDialog(DeviceTimerEditActivityAbs.this, color, bright);
			colordialog.SetOnSaveColorListener(new OnSaveColorListener() {
				
				@Override
				public void onSaveColor(int color, int bright, boolean ison) {
					// TODO Auto-generated method stub
					DeviceTimerEditActivityAbs.this.color = color;
					DeviceTimerEditActivityAbs.this.bright = bright;
					DeviceTimerEditActivityAbs.this.isOn = ison;
					//DeviceTimerEditActivityAbs.this.colordisplay.setBackgroundColor(color);
					colordialog.dismiss();
					DeviceTimerEditActivityAbs.this.colordisplay.setBackgroundColor(color);
				}
			});
			colordialog.show();
			
		}
    	
    }
   	protected View GetPlugTimerActionView() {
   		// TODO Auto-generated method stub
   		
       	  View view = getLayoutInflater().inflate(R.layout.timer_action_spinner, null);
       	 mActionSpinner = (Spinner)view.findViewById(R.id.timer_action_select);
       	 mActionsAdapter =
                   new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mActionTitles);
               mActionSpinner.setAdapter(mActionsAdapter);
             if(mTimer != null)
             {
   	           //EspDeviceFixedTimeTimer timer = (EspDeviceFixedTimeTimer)mTimer;
   	           String action = getTimerAction(mTimer);
   	           for (int i = 0; i < mActionValues.length; i++)
   	           {
   	               if (action.equals(mActionValues[i]))
   	               {
   	                  mActionSpinner.setSelection(i);
   	                  break;
   	               }
   	         }
             }else{
           	  mActionSpinner.setSelection(0);
             }
   		return view;
   	}
   	
    /**
     * 
     * @return the new action need post
     */
    abstract protected String getEditAction();
    
    /**
     * 
     * @return the saved timer action
     */
    abstract protected String getTimerAction(EspDeviceTimer timer);
}
